package com.claire.ffmpegplayer.player;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

import com.claire.ffmpegplayer.sdk.FFmpeg;

public class SurfaceViewPlayer extends SurfaceView implements SurfaceHolder.Callback, FFmpeg.OnSubProgressListener{
    final String TAG = "SurfaceViewPlayer";
    String url;
    int channel;
    public volatile boolean bClose;//是否被关闭，重连
    public static volatile boolean bShow = true;//是否正在显示实时预览页面
    public SurfaceViewPlayer(Context context, String url) {
        this(context);
        this.url = url;
        getHolder().addCallback(this);
        openStream();
//        FFmpeg.player_RegisterCallback(channel,this::onProgressChange);
    }
    public SurfaceViewPlayer(Context context) {
        super(context);
    }

    public void openStream() {
        channel = FFmpeg.player_OpenStream(url);
        System.out.println("openStream" + channel);
    }

    public void drawText(String text) {
        SurfaceHolder holder = getHolder();
        Canvas canvas = null;
        synchronized (holder) {
            try {
                canvas = holder.lockCanvas();//锁定画布，一般在锁定后就可以通过其返回的画布对象Canvas，在其上面画图等操作了。
                if(canvas != null) {
                    if(text.length() != 0) {
                        canvas.drawColor(Color.BLACK);
                        Paint p = new Paint(); //创建画笔
                        p.setColor(Color.WHITE);
                        p.setTextSize(32);
                        canvas.drawText(text, 32, 32, p);
                    } else {
                        canvas.drawColor(0, PorterDuff.Mode.CLEAR);
                    }


                }
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                if (canvas != null) {
                    holder.unlockCanvasAndPost(canvas);//结束锁定画图，并提交改变。
                }
            }
        }
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        System.out.println("surfaceCreated");
//        openStream();
        FFmpeg.player_SetSuface(channel,holder.getSurface());
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
        System.out.println("surfaceChanged");
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        System.out.println("surfaceDestroyed");
    }

    @Override
    public int onProgressChange(long total, long already) {
        System.out.println("onProgressChange" + total);
        return 0;
    }
}
